<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSONP代码优化</title>
</head>

<body>
    <button id='btn'>点击发送请求</button>
    <script>
        // function fn1(data) {
        //     console.log('客户端的fn函数被调用了');
        //     console.log(data);
        // }
    </script>
    <script>
        var btn = document.getElementById('btn');
        btn.onclick = function() {
            jsonp({
                url: 'http://127.0.0.1:8000/better',
                data: {
                    name: 'lisi',
                    age: 18
                },
                success: function(data) {
                    console.log('客户端的fn函数被调用了');
                    console.log(data);
                }
            })
        }

        function jsonp(options) {
            var script = document.createElement('script');
            // 拼接字符串的变量
            var params = '';
            for (var attr in options.data) {
                params += '&' + attr + '=' + options.data[attr];
            }
            var fnName = 'myjsonp' + Math.random().toString().replace('.', '');
            // fn1已经不是全部函数了，我们将它变成全局函数
            window[fnName] = options.success;
            script.src = options.url + '?callback=' + fnName + params;
            document.body.appendChild(script);
            // 添加onload事件，防止多次请求，每次都创建script标签
            script.onload = function() {
                document.body.removeChild(script);
            }
        }
    </script>
</body>

</html>